import {
  getTemplateInspectionItemByPage,
  addTemplateInspectionItem,
  updateTemplateInspectionItem,
  delTemplateInspectionItem,
  exportTemplateInspectionItem,
  getTemplateInspectionItemBySortId,
} from '@/services/quality/templateInspectionItem';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, Row, Col, Select, InputNumber } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { Ellipsis } from '@/components/Ellipsis';
const TemplateInspectionItem: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();

  const [singleoption, setSingleoption] = useState(false); // 单选

  const [multipleselection, setmultipleselection] = useState(false); // 多选
  const [blank, setblank] = useState(false); // 填空
  const [description, setdescription] = useState(false); // 描述
  const theid = props.theid;
  const { TextArea } = Input;

  const ref = useRef(null);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 50,
    },
    {
      title: '选项类型',
      dataIndex: 'optionType',
      width: 100,
      align: 'center',
      sorter: true,

      valueType: 'select',
      request: async () => [
        { value: '单选', label: '单选' },
        { value: '多选', label: '多选' },
        { value: '填空', label: '填空' },
        { value: '描述', label: '描述' },
      ],
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '检查点',
      dataIndex: 'itemName',
      width: 130,
      align: 'center',
      sorter: true,

      // render: (text, record, _, action) => {
      //   return <div>{record.itemName}</div>;
      // },
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '排序',
      dataIndex: 'sortId',
      width: 80,
      valueType: 'digit',
      align: 'center',
      sorter: true,

      defaultSortOrder: 'ascend', //默认升序，降序用descend
      // sorter:(a, b) =>a.sortId -b.sortId,
    },
    {
      title: '检查标准',
      dataIndex: 'inspectionMethod',
      search: false,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    // {
    //   title: '有无详细描述',
    //   dataIndex: 'isDetailDes',
    //   render: (text, record, _, action) => {
    //     return <div>
    //       {record.isDetailDes == '1' ? '有' : record.isDetailDes == '0'?'无':'-'}
    //     </div>;
    //   },
    // },
    // {
    //   title: '有无其他描述',
    //   dataIndex: 'isExtendDes',
    //   render: (text, record, _, action) => {
    //     return <div>
    //       {record.isExtendDes == '1' ? '有' : record.isExtendDes == '0'?'无':'-'}
    //     </div>;
    //   },
    // },
    // {
    //   title: '描述',
    //   dataIndex: 'des',
    // },
    // {
    //   title: '多选选项',
    //   dataIndex: 'descOption',
    // },
    // {
    //   title: '右侧选项',
    //   dataIndex: 'rightOption',
    // },
    // {
    //   title: '备注',
    //   dataIndex: 'memo',
    // },
    // {
    //   title: '创建日期', //表头显示的名称
    //   search: false,
    //   dataIndex: 'createTime',
    // },
    // {
    //   title: '创建人', //表头显示的名称
    //   search: false,
    //   dataIndex: 'createName',
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 120,
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            // console.log(typeof(record.sortId),'数据类型');
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            if (record.optionType == '单选') {
              setSingleoption(true);
            } else if (record.optionType == '多选') {
              setmultipleselection(true);
            } else if (record.optionType == '填空') {
              setblank(true);
            } else if (record.optionType == '描述') {
              setdescription(true);
            }
            form.setFieldsValue({
              des: record.des,
              descOption: record.descOption,
              inspectionMethod: record.inspectionMethod,
              inspectionTemplateId: record.inspectionTemplateId,
              isDetailDes: record.isDetailDes == '1' ? '有' : record.isDetailDes == '0' ? '无' : '',
              isExtendDes: record.isExtendDes == '1' ? '有' : record.isExtendDes == '0' ? '无' : '',
              itemName: record.itemName,
              memo: record.memo,
              optionType: record.optionType,
              rightOption: record.rightOption,
              sortId: record.sortId,
              id: record.id,
              createTime: record.createTime,
              createName: record.createName,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delTemplateInspectionItem({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          const new_params = {
            inspectionTemplateId: theid,
            sortId: res.sortId,
          };
          const new_result = await getTemplateInspectionItemBySortId(new_params);
          if (new_result.data == null) {
            res.inspectionTemplateId = theid;
            if (res.optionType == '单选') {
              res.rightOption = '是|否|无';
              res.isDetailDes = '0'; //描述文本框
              res.isExtendDes = '0'; //多选的其他描述
            }
            if (res.optionType == '多选') {
              res.descOption = '选项A|选项B|选项C';
              res.isDetailDes = '0';
              res.isExtendDes = '1';
            }
            if (res.optionType == '填空') {
              res.isDetailDes = '1';
              res.isExtendDes = '0';
            }
            if (res.optionType == '描述') {
              res.isDetailDes = '1';
              res.isExtendDes = '0';
            }
            console.log(res);
            const result = await addTemplateInspectionItem(res);
            if (result != null) {
              message.success('添加成功');
              setConfirmLoading(false);
              setModalVisit(false);
              actionRef.current!.reload();
            }
          } else {
            message.warning('检验项排序重复');
            setConfirmLoading(false);
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          const res = form.getFieldsValue();
          res.inspectionTemplateId = theid;
          if (res.isDetailDes == '有') {
            res.isDetailDes = '1';
          } else if (res.isDetailDes == '无') {
            res.isDetailDes = '0';
          }
          if (res.isExtendDes == '有') {
            res.isExtendDes = '1';
          } else if (res.isExtendDes == '无') {
            res.isExtendDes = '0';
          }
          console.log(res);
          const result = await updateTemplateInspectionItem(res);
          if (result != null) {
            message.success('修改成功');
            setConfirmLoading(false);
            setModalVisit(false);
            setSingleoption(false);
            setmultipleselection(false);
            setblank(false);
            setdescription(false);
            actionRef.current!.reload();
          }
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  const cancelmodal = async () => {
    setModalVisit(false);
    setSingleoption(false);
    setmultipleselection(false);
    setblank(false);
    setdescription(false);
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="检验项信息查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={{
          labelWidth: 'auto',
          defaultCollapsed: true,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTranNew(ref.current.getFieldsValue());
          //     exportTemplateInspectionItem({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `TemplateInspectionItem.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const res = { ...params, inspectionTemplateId: theid };
          const sorters = sortTran(sort);
          const filters = filterTranNew(res);
          const result = await getTemplateInspectionItemByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          console.log(result.data.content);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1000, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={cancelmodal}
        width={840}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item name="id" label="id" hidden={true}>
            <Input />
          </Form.Item>
          <Row gutter={[50, 0]}>
            <Col span={24}>
              <Form.Item
                name="itemName"
                label="检验点"
                rules={[{ required: true, message: '请输入检验点名称!' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={24}>
              <Form.Item
                name="inspectionMethod"
                label="检查标准"
                // rules={[{ required: true, message: '请输入检查方法!' }]}
              >
                <TextArea autoSize={{ minRows: 2, maxRows: 6 }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="sortId"
                label="排序"
                rules={[{ required: true, message: '请输入排序!' }]}
              >
                <InputNumber min={1} max={1000} precision={0} style={{ width: 260 }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="optionType"
                label="选项类型"
                rules={[{ required: true, message: '请选择选项类型!' }]}
              >
                <Select
                  options={[
                    { value: '单选', label: '单选' },
                    { value: '多选', label: '多选' },
                    { value: '填空', label: '填空' },
                    { value: '描述', label: '描述' },
                  ]}
                  disabled={createOrUpdate}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                name="isDetailDes"
                label="描述文本框"
                hidden={!createOrUpdate}
                // hidden={true}
                // rules={[{ required: true, message: '请输入版本!' }]}
              >
                <Select
                  options={[
                    { value: '1', label: '有' },
                    { value: '0', label: '无' },
                  ]}
                  disabled={blank || description || multipleselection}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="isExtendDes" label="多选其他描述" hidden={!createOrUpdate}>
                <Select
                  options={[
                    { value: '1', label: '有' },
                    { value: '0', label: '无' },
                  ]}
                  disabled={singleoption || blank || description}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={24}>
              <Form.Item
                name="descOption"
                label="多选选项"
                hidden={!createOrUpdate || blank || singleoption || description}
                // rules={[{ required: true, message: '请输入描述!' }]}
              >
                <Input
                  disabled={singleoption || blank || description}
                  placeholder="选项用'|'隔开"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={24}>
              <Form.Item
                name="rightOption"
                label="单选选项"
                hidden={!createOrUpdate || blank || multipleselection || description}
                // rules={[{ required: true, message: '请输入描述!' }]}
              >
                <Input
                  disabled={multipleselection || blank || description}
                  placeholder="选项用'|'隔开"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item name="createName" label="创建人" hidden={!createOrUpdate}>
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="createTime" label="创建时间" hidden={!createOrUpdate}>
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default TemplateInspectionItem;
